import Taro from "@tarojs/taro";
import dayjs from "dayjs";
import {Image, Text, View} from "@tarojs/components";
import {useEffect, useState,useRef} from "react";
import './index.scss'
import SeatBox from "../../components/seatBox";
import {getRealPx} from "../../utils/helper";
import CustomHeader from "../../components/customHeader";

export default () => {
  const {router} = Taro.getCurrentInstance()
  const [seatData, setSeatData] = useState()
  const [planInfo, setPlanInfo] = useState()
  const [seatBoxOptions, setSeatBoxOptions] = useState({})
  const [selectSeat, setSelectSeat] = useState([])
  const [planList, setPlanList] = useState([])
  const [userMember,setUserMember] = useState({})
  const [planId,setPlanId]=useState()
  const [inited,setInited]=useState(true)
  const [regionList, setRegionList] = useState([])
  const [planPriceList, setPlanPriceList] = useState({})
  const [showPlanList,setShowPlanList]=useState(false)
  const selectSeatRef=useRef([])
  const seatResource={
    selected: '',
    unselected0: '',
    unselected1:'',
    unselected2:'',
    unselected3:'',
    unselected4:'',
    unselected5:'',
    unselected6:'',
    unselected7:'',
    bought: '',
    error:''
  }

  const onClickSeat = (evt,pos) => {
    console.log({evt,pos})
    if (evt.label.includes('unselected')) {
      let list=[...selectSeatRef.current]
      setShowPlanList(false)
      if (list.find(item => item.id == evt.id)) {
        list = list.filter(item => item.id != evt.id)
        if(evt.seatType == 'Double' || evt.seatType == 'Multi'){
          list = list.filter(item=>item?.teamValue != evt.teamValue)
        }
      } else {
        if(list.length>=6){
          Taro.$toast('最多选择6个座位')
          return;
        }
        if(evt.seatType == 'Double' || evt.seatType == 'Multi'){
          let arr = []
          seatData.map(res=>{
            res.map(item=>{
              if(item?.teamValue == evt.teamValue){
                arr.push({...item, label: 'selected',pos:{
                  row:item.row-1,
                  col:item.col-1
                }})
              }
            })
          })
          if(list.length + arr.length>6){
            Taro.$toast('选择的座位超过限制')
          }else{
            list.push(...arr)
          }
        }else{
          list.push({...evt, label: 'selected',pos})
        }
      }
      selectSeatRef.current = list
      setSelectSeat(selectSeatRef.current)
    }
  }

  const getShowDate = (date) => {
    const weekList = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const d = dayjs(date)
    if (dayjs().format('YYYY-MM-DD') == date) {
      return `今天 ${d.format('MM月DD日')}`
    } else if (dayjs().add(1, 'day').format('YYYY-MM-DD') == date) {
      return `明天 ${d.format('MM月DD日')}`
    } else if (dayjs().add(2, 'day').format('YYYY-MM-DD') == date) {
      return `后天 ${d.format('MM月DD日')}`
    } else {
      return `${weekList[d.day()]} ${d.format('MM月DD日')}`
    }
  }

  const lockSeat=async ()=>{
    if(!selectSeat.length){
      return Taro.$toast('请先选择座位')
    }
    // console.log(Taro.getStorageSync('user'))
    let noPayOrderNo=''
    await Taro.$get('/cinema-app/api/v1/order/waitpay',{
      userId: Taro.getStorageSync('user')?.userId
    }).then(res=>{
      if(res.code==1&&res.content){
        noPayOrderNo=res.content
      }
    })
    if(noPayOrderNo){
      const noPayRes=await Taro.showModal({
        title: '提示',
        content: '您之前购买的特价票还未付款',
        cancelText:'取消订单',
        confirmText:'立即付款',
      })
      if(noPayRes.confirm){
        Taro.redirectTo({
          url: `/mainPages/confirmOrder/index?id=${noPayOrderNo}`
        })
        return;
      }else{
        await Taro.$post('/cinema-app/api/v1/order/cancel',{
          orderId:noPayOrderNo
        })
      }
    }
    Taro.showLoading()
    Taro.$post('/cinema-app/api/v1/order/create', {
      cinemaId:planInfo.cinemaId,
      planId: router.params.id,
      seatList: selectSeat.map(item=>{
        return {
          priceId: item.priceId,
          seatId: item.id
        }
      }),
      userId: Taro.getStorageSync('user')?.userId
    }).then(res=>{
      Taro.hideLoading()
      if (res.code == '1') {
        Taro.redirectTo({
          url: `/mainPages/confirmOrder/index?id=${res.content.orderCode}`
        })
      }else{
        Taro.$toast(res.message)
      }
    })
  }


  const fetchPlan=()=>{
    Taro.$get('/cinema-app/api/v1/plan/byCinemaAndFilm', {
      cinemaId: planInfo.cinemaId,
      filmId: planInfo.filmId
    }).then(res => {
      if (res.code == '1') {
        const planListRes=res.content.find(item=>item.planDate==planInfo.planDate)
        if(planListRes){
          setPlanList(planListRes.planList.map(r => {
            r.showTimeStart = dayjs(r.showTimeStart).format('HH:mm')
            r.showTimeEnd = dayjs(r.showTimeEnd).format('HH:mm')
            r.listingPrice = parseFloat(r.listingPrice)
            r.standardPrice = parseFloat(r.standardPrice)
            return r
          }))
        }
      }
    })
  }

  useEffect(()=>{
    if(planInfo){
      fetchPlan()
    }
  },[planInfo])

  useEffect(()=>{
    setPlanId(router.params.id)
    Taro.$get('/wallet/paid/myMember').then(res=>{
      setUserMember(res.content)
    })
  },[])

  const init=async () => {
    Taro.showLoading()
    setInited(false)
    setSelectSeat([])
    const planInfoRes = await Taro.$get('/cinema-app/api/v1/plan/price', {
      planId: planId
    })
    if (planInfoRes.code != '1'){
      Taro.$toast(planInfoRes.message)
      return;
    }
    setPlanInfo({
      ...planInfoRes.content,
      showDate: `${getShowDate(planInfoRes.content.planDate)} ${planInfoRes.content.showTimeStart.substr(11, 5)}-${planInfoRes.content.showTimeEnd.substr(11, 5)}`
    })
    await Taro.$get('/cinema-app/api/v1/seat/byPlan', {
      planId: planId
    },'1').then(res => {
      if (res.code == '1') {
        const seatInfo = {
          maxCol: 0,
          maxRow: 0,
          minCol: 100,
          minRow: 100,
          seats: {}
        }
        const tmpSeatData = []
        setRegionList(res.content.regionList)
        const planPriceListTmp={}
        res.content.regionList.forEach((item,index)=>{
          planPriceListTmp[item.regionId]={
            priceId:item.salePriceId,
            salePrice:item.salePrice,
            discountAmount:item.discountAmount,
            label:`unselected${index%8}`
          }
        })
        setPlanPriceList(planPriceListTmp)
        res.content.seatList.forEach(item => {
          const row = parseInt(item.seatX)
          const col = parseInt(item.seatY)
          seatInfo.minRow = row > seatInfo.minRow ? seatInfo.minRow : row
          seatInfo.minCol = col > seatInfo.minCol ? seatInfo.minCol : col
          seatInfo.maxRow = row < seatInfo.maxRow ? seatInfo.maxRow : row
          seatInfo.maxCol = col < seatInfo.maxCol ? seatInfo.maxCol : col
          seatInfo.seats[`${row}_${col}`] = item
        })
        for (let row = seatInfo.minRow; row <= seatInfo.maxRow; row++) {
          let rowSeats = []
          for (let col = seatInfo.minCol; col <= seatInfo.maxCol; col++) {
            const seat = seatInfo.seats[`${row}_${col}`]
            rowSeats.push(seat ? {
              ...seat,
              col: seat.seatY,
              row: seat.seatX,
              ...planPriceListTmp[seat.regionId]||{},
              label: seat.status == 'Selled'?'bought':planPriceListTmp[seat.regionId]?.label,
            } : null)
          }
          tmpSeatData.push(rowSeats)
        }
        setSeatData(tmpSeatData)
        console.log({tmpSeatData,seatInfo})
        let query = Taro.createSelectorQuery()
        query.selectAll('.part-3').boundingClientRect((rectRes) => {
          setSeatBoxOptions({
            resource: seatResource,
            boxW: getRealPx(750),
            boxH: rectRes[0].height-getRealPx(200),
            boxT: rectRes[0].top,
            minMapSize: {
              w: getRealPx(400),
              h: getRealPx(200),
            }
          })
          Taro.hideLoading()
          setInited(true)
          if(showPlanList){
            Taro.$toast(`您选择的是${getShowDate(planInfo.planDate)}的场次`)
          }
        }).exec()
      }else{
        Taro.$toast(res.message)
      }
    })
  }

  useEffect(()=>{
    if(planId){
      init()
    }
  }, [planId]);
  return (
    <View className='seat'>
      <View className='page-content'>
        <CustomHeader>
          {
            !planInfo ?'':
              <View className='header'>
                <View className='row-1 ellipsis'>{decodeURIComponent(router.params.filmName)}</View>
                <View className='row-2'>{planInfo.filmVersion}{planInfo.filmLanguage}</View>
              </View>
          }
        </CustomHeader>
        <View className='part-1 flex-cc' style={process.env.TARO_ENV == 'h5'?{paddingTop:'40px'}:null}>
          <View className='item flex-cs'>
            <Image src={seatResource['bought']} className='i-1' />
            <Text className='i-2'>已售</Text>
          </View>
          {
            regionList.map((item)=>{
              return (
                <View className='item flex-cs' key={item.regionName}>
                  <Image className='i-1'
                    src={seatResource[planPriceList[item.regionId]?planPriceList[item.regionId].label:`unselected0`]}
                  ></Image>
                  <Text className='i-2'>{item.regionName}</Text>
                </View>
              )
            })
          }
        </View>
        <View className='part-2 flex-cc'>
          <Image className='i-1' src={require('@/images/ticket/screen.png')}></Image>
          <Text className='i-2'>屏幕方向</Text>
        </View>
        <View className='part-3'>
          {
            !inited?'':
              <SeatBox seatData={seatData} options={seatBoxOptions} selectSeat={selectSeat}
                onClickSeat={onClickSeat}
              ></SeatBox>
          }
        </View>
        {
          !planInfo ? '' :
            <View className='part-4'>
              <View className='part-con'>
                <View className='col-1'>
                  <View className='row-1 ellipsis'>{decodeURIComponent(router.params.filmName)}</View>
                  <View className='row-2'>{planInfo.showDate}</View>
                </View>
                <View className='col-2' onClick={()=>{
                  setShowPlanList(!showPlanList)
                }}
                >{showPlanList?'收起':'切换'}场次</View>
              </View>
              {
                showPlanList?'':
                  <View className='row-3'>
                    {
                      selectSeat.map((item,idx)=>{
                        return (
                          <View className='item' key={idx} onClick={()=>{
                            onClickSeat({...item,label:"unselected"},item.pos)
                          }}
                          >
                            <View className='i-1'>{`${item.seatRow}排${item.seatColumn}座`}</View>
                            <View className='i-3'>
                              <Text className='i-4'>¥{item.salePrice}</Text>
                              {item.discountAmount?<Text className='i-5'>已优惠{item.discountAmount}元</Text>:null}
                            </View>
                          </View>
                        )
                      })
                    }
                  </View>
              }
              {
                !showPlanList?'':
                <View className='row-4'>
                  {
                    planList.map(item=>{
                      return (
                        <View key={item.id} className={`item ${item.id==planId?'active':''}`} onClick={()=>{
                          setPlanId(item.id)
                        }}
                        >
                          <View className='i-1'>{item.showTimeStart}</View>
                          <View className='i-2'>{item.filmLanguage}{item.filmVersion}</View>
                          <View className='i-3'>
                            <Text className='i-4'>¥{userMember.status == '1'?item.memberPrice:item.salePrice}起</Text>
                          </View>
                        </View>
                      )
                    })
                  }
                </View>
              }
            </View>
        }
        <View className='part-5 flex-cc'>
          <View className='btn flex-cc' onClick={lockSeat}>确认选座</View>
        </View>
      </View>
    </View>
  )
}
